package com.jse.util.concurrent.new1.collection;


import org.junit.Test;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * CopyOnWriteArraySet实现了读写分离
 * 
 * @author Administrator
 *
 */
public class CopyOnWriteArraySetTest {
	
	@Test
	public void testList() {
		CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
		Collections.addAll(list, 1, 2, 3, 1);
		for (Integer i : list) {
			list.add(4);
			System.out.println(i);
		}
		System.out.println("set的长度为：" + list.size());
	}
	
	/**
	 * 循环的时候中间添加数据
	 */
	@Test
	public void testLoopAdd() {
		CopyOnWriteArraySet<Integer> set = new CopyOnWriteArraySet<>();
		Collections.addAll(set, 1, 2, 3, 1);
		for (Integer i : set) {
			set.add(4);
			System.out.println(i);
		}
		System.out.println("set的长度为：" + set.size());
	}
	
	/**
	 * 即使用Collections中的同步synchronizedSet在读取时，对集合进行增删操作一样抛异常
	 */
	@Test
	public void testSynSet() {
		Set<String> set = new HashSet<String>();
		Collections.addAll(set, "a", "b", "c");
		Set<String> results = Collections.synchronizedSet(set);
		for (String s : results) {
//			results.remove(s);
			System.out.println(s);
		}
	}
	
	@Test
	public void testLoop() {
		Set<String> oldSet = new HashSet<>();
		Map<String, Object> map = new HashMap<>();
		map.put("a", 1);
		map.put("b", 2);
		map.put("c", 3);
		CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
		Collections.addAll(set, "a", "b", "c", "d");
		Collections.addAll(oldSet, "e", "f", "g", "h", "i", "j", "k", "l");
		
		for (String e : set) {
			System.out.print(" " + e);
		}
		System.out.println("=========");
		//无序，可以添加重复的值，但是重复值取出来只有一个
		for (int i = 0; i < 100; i++) {
			oldSet.add(String.valueOf(i));
		}
		
		for (String s : oldSet) {
			//fast-failed
//			oldSet.remove(s);
			System.out.print(" " + s);
		}
		System.out.println("=========");
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			System.out.print(" " + entry.getValue());
		}
	}



}
